/*
 * @Author: CPS
 * @Date: 2020-08-11 00:24:10
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-24 23:00:23
 * @Projectname Electron-fileWatcher
 * @file_path D:\CPS\MyProject\Electron-fileWatcher\src\renderer\pages\fileWatcher\js\config\events\config.event.js
 * @Filename config.event.js
 */
'use strict'
/**
 * 通过遍历,往上层查找对应clasname的父元素
 *
 * @param      {元素标签}  Element   The element
 * @param      {<string>}  findName  The find name
 * @param      {递归次数}  T         { parameter_description }
 * @return     {<type>}  The parent by class name.
 */
function getParentByClassName(Element, findName, T = 5) {
  if (T <= 0) return

  if (Element.className == findName) return Element

  let parent = Element.parentElement
  if (parent) {
    if (parent.className == findName) {
      return parent
    }
    T = T - 1
    return getParentByClassName(parent, findName, T)
  }
}

/*添加前缀函数*/
function prefix(name) {
  return 'config__' + name
}

function clickHandlers(target, config) {
  let parent
  let closeList = [
    'config__component'
  ]
  let tar = target.id ? target.id : target.className

  switch (tar) {
    // 关闭按钮
    case 'config__btn-close':
      parent = getParentByClassName(target, prefix('component'))
      // 通过设置透明度获取动画效果
      parent.style.opacity = 0
      parent.style.transform = 'translate(150%)'
      break;

    case 'config__eachSetting':
      // 通过获取按钮的名字,弹出对应的页面
      let pageName = target.getElementsByTagName('strong')[0].innerHTML
      if (pageName) {
        config.show(pageName)
      }
      break;

    default:
      if (closeList.indexOf(tar) != -1) {
        // 通过设置透明度获取动画效果
        config.el.style.transform = 'translate(150%)'
        config.el.style.opacity = 0
      } else {
        log('当前点击' + tar)
      }
      break;
  }
}

export default (configObject) => {
  if (!configObject.el) return

  log('载入configEvents')

  // 点击事件
  configObject.el.addEventListener('click', (e) => {
    let tar = e.target.id ? e.target.id : e.target.className
    if (!tar) return
    clickHandlers(e.target, configObject)
  }, true)


  // 监听 show 自定义事件
  configObject.el.addEventListener('show', (e) => {
    if (configObject.el.style.transform == 'translate(150%)') configObject.el.style.transform = 'translate(0)'
    if (configObject.el.style.opacity == 0) configObject.el.style.opacity = 1
  })
}